<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas style="border: 2px solid black" width="100" height="100"></canvas>
    <script>
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");
        function Subject() {
            const listeners = []
            return {
                publish(val) {
                    for (let listener of listeners) {
                        listener(val)
                    }
                },
                subscribe(cb) {
                    listeners.push(cb)
                }
            }
        }
        const subject = Subject()
        setInterval(() => {
            ctx.clearRect(0, 0, 100, 100)
            subject.publish()
        }, 100)
        // 食物列表
        function BonusList() {
            const list = [];
            const getBonus = () => {
                const bonus = [
                    Math.floor(Math.random() * 100),
                    Math.floor(Math.random() * 100),
                ];
                list.push(bonus);
                if (list.length < 20) {
                    getBonus();
                }
            };
            subject.subscribe(getBonus);
            const render = () => {
                for (let bonus of list) {
                    ctx.fillStyle = "red";
                    ctx.fillRect(bonus[0], bonus[1], 1, 1);
                }
            };
            subject.subscribe(render);
            return {
                list,
            };
        }
        const bonusList = BonusList();
        // 游戏
        function Game() {
            const judge = () => {
                const [head, ...body] = snake.list;
                console.log(head);
                for (let key in bonusList.list) {
                    const bonus = bonusList.list[key];
                    if (head[0] === bonus[0] && head[1] === bonus[1]) {
                        const nextHead = [];
                        nextHead[0] = head[0] + snake.direction[0];
                        nextHead[1] = head[1] + snake.direction[1];
                        snake.list.unshift(nextHead);
                        bonusList.list.splice(key, 1);
                    }
                }
                if (head[0] < 0 || head[0] > 100 || head[1] < 0 || head[1] > 100) {
                    alert("撞墙咯");
                }
                for (let item of body) {
                    if (item[0] === head[0] && item[1] === head[1]) {
                        alert("撞到自己咯");
                    }
                }
            };
            subject.subscribe(judge);
        }
        Game();
    </script>
</body>

</html>